import {
  documentBulkDeletes,
  documentCreate,
  documentPagination,
  documentUpdate,
} from '@/services/swagger/document';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { FooterToolbar, ModalForm, PageContainer, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import type { UploadProps } from 'antd';
import { Button, Drawer, message, Upload } from 'antd';
import React, { useRef, useState } from 'react';
import { userStorage } from '../../userStorage';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';

const props: UploadProps = {
  name: 'file',
  action: '/api/module/Upload/file/credit',
  headers: {
    authorization: userStorage.getToken() as string,
  },
  async onChange(info) {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      const responseData = info.file.response;
      if (responseData && responseData.success) {
        await documentCreate({ title: info.file.name, path: responseData.data.src });
        message.success(`${info.file.name} 文件上传成功`);
      } else {
        message.error(`上传失败: ${responseData.message || '未知错误'}`);
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 文件上传失败.`);
    }
  },
};

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.DocumentCreateInputModel) => {
  const hide = message.loading('');
  // try {
  //   await documentCreate({ ...fields });
  //   hide();
  //   message.success('添加成功');
  //   return true;
  // } catch (error) {
  //   hide();
  //   message.error('添加失败, 请重试!');
  //   return false;
  // }
  hide();
  return true;
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('Configuring');
  try {
    console.log('更新：', fields);
    await documentUpdate({
      id: fields.id,
    });
    hide();

    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败, 请重试!');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.DocumentOutputModel[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    const ids = {
      ids: selectedRows.map((row) => row.id).join(','), // 示例 ID 列表
    } as API.CustBulkDeletesParams;

    await documentBulkDeletes(ids);
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败, 请重试！');
    return false;
  }
};

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.DocumentOutputModel>();
  const [selectedRowsState, setSelectedRows] = useState<API.DocumentOutputModel[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<API.DocumentOutputModel>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.document.list.updateForm.title.nameLabel"
          defaultMessage="Title"
        />
      ),
      dataIndex: 'title',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.document.list.updateForm.path.nameLabel"
          defaultMessage="File Path"
        />
      ),
      dataIndex: 'path',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleStatus" defaultMessage="Status" />,
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '未开始',
          status: 'Default',
        },
        1: {
          text: '排队中',
          status: 'Processing',
        },
        2: {
          text: '正在执行',
          status: 'Processing',
        },
        3: {
          text: '准备分析',
          status: 'Processing',
        },
        4: {
          text: '分析中',
          status: 'Warning',
        },
        5: {
          text: '完成分析',
          status: 'Success',
        },
      },
    },
    // {
    //   title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
    //   dataIndex: 'option',
    //   valueType: 'option',
    //   render: (_, record) => [
    //     <a
    //       key="update"
    //       onClick={() => {
    //         handleUpdateModalOpen(true);
    //         setCurrentRow(record);
    //       }}
    //     >
    //       <FormattedMessage id="pages.user.list.update" defaultMessage="Update" />
    //     </a>,
    //   ],
    // },
  ];

  return (
    <PageContainer>
      <ProTable<API.DocumentUpdateInputModel, API.DocumentPaginationParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.document.title',
          defaultMessage: 'Document',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        request={documentPagination}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title={intl.formatMessage({
          id: 'pages.document.list.createForm.newDocument',
          defaultMessage: 'New Document',
        })}
        width="400px"
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.DocumentCreateInputModel);
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <Upload {...props}>
          <Button icon={<UploadOutlined />}>点击上传</Button>
        </Upload>
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {/* {currentRow?.summary && (
          <ProDescriptions<API.DocumentOutputModel>
            column={2}
            title={currentRow?.title}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<API.DocumentOutputModel>[]}
          />
        )} */}
        <div style={{ whiteSpace: 'pre-wrap' }}>{currentRow?.summary || ''}</div>
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
